package com.it.emall.controller;

import com.it.emall.domain.Comments;
import com.it.emall.service.CommentsService;
import com.it.emall.utils.JwtHelper;
import com.it.emall.utils.ResponseUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/wx/comments")
public class CommentsController {


    @Autowired
    private CommentsService commentsService;

    /**
     * 用户发表评论
     * @param token 用户ID
     * @param recipeId 食谱ID
     * @param content 评论内容
     * @return 响应数据
     */
    @PostMapping("/add")
    public Object addComment(@RequestHeader("token") String token, @RequestParam int recipeId, @RequestParam String content) {
        Integer userId = JwtHelper.verifyTokenAndGetUserId(token);
        int result = commentsService.addComment(userId, recipeId, content);
        if (result == 0) {
            return ResponseUtils.ok("评论成功");
        } else {
            return ResponseUtils.fail(500, "评论失败");
        }
    }

    /**
     * 获取某个食谱的所有评论
     * @param recipeId 食谱ID
     * @return 食谱的所有评论
     */
    @GetMapping("/list")
    public Object getCommentsByRecipe(@RequestParam int recipeId) {
        List<Comments> comments = commentsService.getCommentsByRecipe(recipeId);
        return ResponseUtils.ok(comments);
    }

    /**
     * 删除自己的评论
     * @param token 用户ID
     * @param commentId 评论ID
     * @return 响应数据
     */
    @DeleteMapping("/delete")
    public Object deleteComment(@RequestHeader("token") String token, @RequestParam int commentId) {
        Integer userId = JwtHelper.verifyTokenAndGetUserId(token);
        int result = commentsService.deleteComment(userId, commentId);
        if (result == 0) {
            return ResponseUtils.ok("删除评论成功");
        } else {
            return ResponseUtils.fail(500, "删除评论失败");
        }
    }
}
